﻿using CommonLib.Pattern;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace CommonLib
{
	//执行UI跳转事件 在UIView切换时保持协程的执行
	//并进行事件的监听与注册
	public class UIViewManagerBase : Singleton<UIViewManagerBase>
	{
		protected ListernerSystem m_Listener = new ListernerSystem();

		Stack<UIViewBase> m_StackView;
		public UIViewBase CurrentView => m_StackView.Count > 0 ? m_StackView.Peek() : null;
		public Stack<UIViewBase> StackView => m_StackView ?? new Stack<UIViewBase>(); 
		public UIViewManagerBase()
		{
			//初始化栈
			m_StackView = new Stack<UIViewBase>();
		}

		/// <summary>
		/// 跳转View场景
		/// 将跳转的协程放在ViewManager中防止在执行切换过程中 协程挂载的物体被隐藏导致协程无法继续执行
		/// </summary>
		/// <param name="_viewClose"></param>
		/// <param name="_viewOpen"></param>
		public virtual void ChangeView(UIViewBase _viewClose, UIViewBase _viewOpen) {
			
		}

		public virtual void ChangeView(UIViewBase _viewOpen)
		{
			//Handel Pre View 
			if(_viewOpen.ViewType == ViewType.Normal)
			{
				if(null != CurrentView)
				{
					CurrentView.Close();
					StackView.Pop();
				}
			}else if( _viewOpen.ViewType == ViewType.Pause)
			{
				CurrentView?.Pause();
			}
			//Open This View
			_viewOpen?.Open();
		}

		#region Later Monobehavier
		/*
		IEnumerator CorChangeView(UIViewBase _viewClose, UIViewBase _viewOpen) {
			//关闭和开启其中一个为等待则进行等待
			if ( _viewClose.ViewType.m_ViewTypeClose == ViewType.wait || _viewOpen.ViewType.m_ViewTypeOpen == ViewType.wait) {
				yield return CorViewOpenOrClose(_viewClose, false);
				yield return CorViewOpenOrClose(_viewOpen, true);
			}
			else
			{
				StartCoroutine(CorViewOpenOrClose(_viewClose, false));
				StartCoroutine(CorViewOpenOrClose(_viewOpen, true));
				yield return null;
			}
		}
			*/
		/*
	IEnumerator CorViewOpenOrClose(UIViewBase _view, bool _isOpen) {
		if (_isOpen)
		{
			yield return _view.CorOpen();
		}
		else
		{
			yield return _view.CorClose();
		}

		Dictionary<string, TweenAnimBase> TempAnimation = _isOpen ? _view.AnimationOpen : _view.AnimationClose;
		foreach (var anim in TempAnimation)
		{
			anim.Value.Excute();
		}
		yield return null;
		
	}
	*/
		#endregion


		#region Pattern Listern

		public void Register(string key, RegisterEvent registerEvent) => m_Listener.Register(key, registerEvent);
		public void Deregister(string key) => m_Listener.Deregister(key);
		public void Respon(string key, object param = null) => m_Listener.Respon(key, param);
		#endregion
	}
}